<template>
  <!-- 仪表盘 -->
  <div class="dashboard-container">
    <!-- 顶部统计卡片 -->
    <!-- <div class="stats-cards">
      <ACard class="stat-card" :bordered="false">
        <div class="stat-content">
          <div class="stat-icon user-icon">
            <UserOutlined />
          </div>
          <div class="stat-info">
            <div class="stat-number">
              {{ userStats.total }}
            </div>
            <div class="stat-label">
              总用户数
            </div>
            <div class="stat-trend positive">
              <ArrowUpOutlined /> +12.5%
            </div>
          </div>
        </div>
      </ACard>

      <ACard class="stat-card" :bordered="false">
        <div class="stat-content">
          <div class="stat-icon order-icon">
            <ShoppingCartOutlined />
          </div>
          <div class="stat-info">
            <div class="stat-number">
              {{ orderStats.total }}
            </div>
            <div class="stat-label">
              今日订单
            </div>
            <div class="stat-trend positive">
              <ArrowUpOutlined /> +8.2%
            </div>
          </div>
        </div>
      </ACard>

      <ACard class="stat-card" :bordered="false">
        <div class="stat-content">
          <div class="stat-icon revenue-icon">
            <DollarOutlined />
          </div>
          <div class="stat-info">
            <div class="stat-number">
              ¥{{ revenueStats.total.toLocaleString() }}
            </div>
            <div class="stat-label">
              今日收入
            </div>
            <div class="stat-trend negative">
              <ArrowDownOutlined /> -2.1%
            </div>
          </div>
        </div>
      </ACard>

      <ACard class="stat-card" :bordered="false">
        <div class="stat-content">
          <div class="stat-icon visit-icon">
            <EyeOutlined />
          </div>
          <div class="stat-info">
            <div class="stat-number">
              {{ visitStats.total }}
            </div>
            <div class="stat-label">
              页面访问
            </div>
            <div class="stat-trend positive">
              <ArrowUpOutlined /> +15.3%
            </div>
          </div>
        </div>
      </ACard>
    </div> -->

    <!-- 图表区域 -->
    <div class="charts-section">
      <div class="chart-row">
        <!-- 销售趋势图 -->
        <ACard title="销售趋势" class="chart-card" :bordered="false">
          <template #extra>
            <RadioGroup v-model:value="salesPeriod" size="small" @change="updateSalesData">
              <RadioButton value="7d">
                7天
              </RadioButton>
              <RadioButton value="30d">
                30天
              </RadioButton>
              <RadioButton value="90d">
                90天
              </RadioButton>
            </RadioGroup>
          </template>
          <div class="chart-container">
            <VChart
              class="chart"
              :option="salesChartOption"
              :autoresize="true"
              @click="onSalesChartClick"
            />
          </div>
        </ACard>

        <!-- 用户分布饼图 -->
        <ACard title="用户分布" class="chart-card" :bordered="false">
          <div class="chart-container">
            <VChart
              class="chart"
              :option="userDistributionOption"
              :autoresize="true"
            />
          </div>
        </ACard>
      </div>

      <div class="chart-row">
        <!-- 实时数据监控 -->
        <ACard title="实时数据监控" class="chart-card" :bordered="false">
          <template #extra>
            <ASwitch
              v-model:checked="realTimeEnabled"
              checked-children="开启"
              un-checked-children="关闭"
              @change="toggleRealTime"
            />
          </template>
          <div class="chart-container">
            <VChart
              class="chart"
              :option="realTimeChartOption"
              :autoresize="true"
            />
          </div>
        </ACard>

        <!-- 地区销售分布 -->
        <ACard title="地区销售分布" class="chart-card" :bordered="false">
          <div class="chart-container">
            <VChart
              class="chart"
              :option="regionChartOption"
              :autoresize="true"
            />
          </div>
        </ACard>
      </div>

      <div class="chart-row">
        <!-- 最近活动 -->
        <ACard title="最近活动" class="activity-card" :bordered="false">
          <div class="activity-list">
            <div v-for="activity in recentActivities" :key="activity.id" class="activity-item">
              <div class="activity-avatar">
                <AAvatar :src="activity.avatar" :style="{ backgroundColor: activity.color }">
                  {{ activity.name.charAt(0) }}
                </AAvatar>
              </div>
              <div class="activity-content">
                <div class="activity-title">
                  {{ activity.title }}
                </div>
                <div class="activity-desc">
                  {{ activity.description }}
                </div>
                <div class="activity-time">
                  {{ activity.time }}
                </div>
              </div>
              <div class="activity-status">
                <ATag :color="activity.status === 'success' ? 'green' : activity.status === 'warning' ? 'orange' : 'blue'">
                  {{ activity.statusText }}
                </ATag>
              </div>
            </div>
          </div>
        </ACard>

        <!-- 快速操作 -->
        <ACard title="快速操作" class="quick-actions-card" :bordered="false">
          <div class="quick-actions">
            <div v-for="action in quickActions" :key="action.id" class="action-item" @click="handleQuickAction(action)">
              <div class="action-icon" :style="{ backgroundColor: action.color }">
                <component :is="action.icon" />
              </div>
              <div class="action-label">
                {{ action.label }}
              </div>
            </div>
          </div>
        </ACard>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <ACard title="最新订单" :bordered="false">
        <ATable
          :columns="orderColumns"
          :data-source="recentOrders"
          :pagination="{ pageSize: 5, showSizeChanger: false }"
          size="middle"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'status'">
              <ATag :color="getStatusColor(record.status)">
                {{ record.status }}
              </ATag>
            </template>
            <template v-if="column.key === 'amount'">
              <span class="amount">¥{{ record.amount.toLocaleString() }}</span>
            </template>
            <template v-if="column.key === 'action'">
              <AButton type="link" size="small">
                查看详情
              </AButton>
            </template>
          </template>
        </ATable>
      </ACard>
    </div>
  </div>
</template>

<script setup>
import { Avatar as AAvatar, Switch as ASwitch, RadioButton, RadioGroup } from 'ant-design-vue'
import { BarChart, GaugeChart, LineChart, PieChart } from 'echarts/charts'
import { DataZoomComponent, GridComponent, LegendComponent, TitleComponent, ToolboxComponent, TooltipComponent } from 'echarts/components'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import VChart from 'vue-echarts'
// 注册ECharts组件
use([
  CanvasRenderer,
  LineChart,
  PieChart,
  BarChart,
  GaugeChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent,
  ToolboxComponent,
])

// 统计数据
const userStats = reactive({
  total: 12580,
})

const orderStats = reactive({
  total: 1234,
})

const revenueStats = reactive({
  total: 98765,
})

const visitStats = reactive({
  total: 45678,
})

// 销售数据周期
const salesPeriod = ref('7d')

// 实时监控开关
const realTimeEnabled = ref(true)
let realTimeTimer = null
const realTimeData = ref([])
const realTimeLabels = ref([])

// 销售趋势图配置
const salesChartOption = computed(() => {
  const data7d = [
    { date: '01-15', value: 12000 },
    { date: '01-16', value: 15000 },
    { date: '01-17', value: 18000 },
    { date: '01-18', value: 16000 },
    { date: '01-19', value: 22000 },
    { date: '01-20', value: 25000 },
    { date: '01-21', value: 28000 },
  ]

  const data30d = Array.from({ length: 30 }, (_, i) => ({
    date: `${String(i + 1).padStart(2, '0')}`,
    value: Math.floor(Math.random() * 20000) + 10000,
  }))

  const data90d = Array.from({ length: 90 }, (_, i) => ({
    date: `${String(i + 1).padStart(2, '0')}`,
    value: Math.floor(Math.random() * 30000) + 15000,
  }))

  const dataMap = {
    '7d': data7d,
    '30d': data30d,
    '90d': data90d,
  }

  const currentData = dataMap[salesPeriod.value]

  return {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(50, 50, 50, 0.9)',
      borderColor: '#333',
      textStyle: {
        color: '#fff',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: currentData.map(item => item.date),
      axisLine: {
        lineStyle: {
          color: '#e8e8e8',
        },
      },
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#e8e8e8',
        },
      },
      splitLine: {
        lineStyle: {
          color: '#f0f0f0',
        },
      },
    },
    series: [
      {
        name: '销售额',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          width: 3,
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              { offset: 0, color: '#667eea' },
              { offset: 1, color: '#764ba2' },
            ],
          },
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(102, 126, 234, 0.3)' },
              { offset: 1, color: 'rgba(102, 126, 234, 0.05)' },
            ],
          },
        },
        data: currentData.map(item => item.value),
        animationDuration: 2000,
        animationEasing: 'cubicOut',
      },
    ],
  }
})

// 用户分布饼图配置
const userDistributionOption = ref({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)',
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    top: 'center',
  },
  series: [
    {
      name: '用户分布',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['60%', '50%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2,
      },
      label: {
        show: false,
        position: 'center',
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 20,
          fontWeight: 'bold',
        },
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)',
        },
      },
      labelLine: {
        show: false,
      },
      data: [
        { value: 4500, name: '新用户', itemStyle: { color: '#1890ff' } },
        { value: 3500, name: '活跃用户', itemStyle: { color: '#52c41a' } },
        { value: 2000, name: '沉睡用户', itemStyle: { color: '#faad14' } },
      ],
      animationType: 'scale',
      animationEasing: 'elasticOut',
      animationDelay(idx) {
        return Math.random() * 200
      },
    },
  ],
})

// 实时数据图表配置
const realTimeChartOption = computed(() => {
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985',
        },
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: realTimeLabels.value,
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 100,
    },
    series: [
      {
        name: 'CPU使用率',
        type: 'line',
        smooth: true,
        symbol: 'none',
        lineStyle: {
          width: 2,
          color: '#ff6b6b',
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(255, 107, 107, 0.3)' },
              { offset: 1, color: 'rgba(255, 107, 107, 0.05)' },
            ],
          },
        },
        data: realTimeData.value,
        animationDuration: 0,
      },
    ],
  }
})

// 地区销售分布图表配置
const regionChartOption = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true,
  },
  xAxis: {
    type: 'value',
    boundaryGap: [0, 0.01],
  },
  yAxis: {
    type: 'category',
    data: ['北京', '上海', '广州', '深圳', '杭州', '成都'],
  },
  series: [
    {
      name: '销售额',
      type: 'bar',
      data: [18203, 23489, 29034, 104970, 131744, 630230],
      itemStyle: {
        color(params) {
          const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272']
          return colors[params.dataIndex % colors.length]
        },
        borderRadius: [0, 4, 4, 0],
      },
      animationDelay(idx) {
        return idx * 100
      },
    },
  ],
  animationEasing: 'elasticOut',
  animationDelayUpdate(idx) {
    return idx * 5
  },
})

// 最近活动数据
const recentActivities = ref([
  {
    id: 1,
    name: '张三',
    avatar: '',
    color: '#1890ff',
    title: '新用户注册',
    description: '用户张三完成了账户注册',
    time: '2分钟前',
    status: 'success',
    statusText: '成功',
  },
  {
    id: 2,
    name: '李四',
    avatar: '',
    color: '#52c41a',
    title: '订单支付',
    description: '订单 #12345 支付成功',
    time: '5分钟前',
    status: 'success',
    statusText: '已完成',
  },
  {
    id: 3,
    name: '王五',
    avatar: '',
    color: '#faad14',
    title: '退款申请',
    description: '订单 #12346 申请退款',
    time: '10分钟前',
    status: 'warning',
    statusText: '处理中',
  },
  {
    id: 4,
    name: '赵六',
    avatar: '',
    color: '#f5222d',
    title: '系统登录',
    description: '管理员赵六登录系统',
    time: '15分钟前',
    status: 'info',
    statusText: '正常',
  },
])

// 快速操作数据
const quickActions = ref([
  { id: 1, label: '新增用户', icon: 'PlusOutlined', color: '#1890ff' },
  { id: 2, label: '系统设置', icon: 'SettingOutlined', color: '#52c41a' },
  { id: 3, label: '数据报表', icon: 'FileTextOutlined', color: '#faad14' },
  { id: 4, label: '团队管理', icon: 'TeamOutlined', color: '#722ed1' },
])

// 订单表格列定义
const orderColumns = [
  { title: '订单号', dataIndex: 'orderNo', key: 'orderNo' },
  { title: '客户', dataIndex: 'customer', key: 'customer' },
  { title: '金额', dataIndex: 'amount', key: 'amount' },
  { title: '状态', dataIndex: 'status', key: 'status' },
  { title: '时间', dataIndex: 'createTime', key: 'createTime' },
  { title: '操作', key: 'action' },
]

// 最新订单数据
const recentOrders = ref([
  {
    key: '1',
    orderNo: 'ORD001',
    customer: '张三',
    amount: 1299,
    status: '已完成',
    createTime: '2024-01-21 10:30',
  },
  {
    key: '2',
    orderNo: 'ORD002',
    customer: '李四',
    amount: 2599,
    status: '进行中',
    createTime: '2024-01-21 09:15',
  },
  {
    key: '3',
    orderNo: 'ORD003',
    customer: '王五',
    amount: 899,
    status: '待支付',
    createTime: '2024-01-21 08:45',
  },
  {
    key: '4',
    orderNo: 'ORD004',
    customer: '赵六',
    amount: 3299,
    status: '已完成',
    createTime: '2024-01-20 16:20',
  },
  {
    key: '5',
    orderNo: 'ORD005',
    customer: '钱七',
    amount: 1899,
    status: '已取消',
    createTime: '2024-01-20 14:10',
  },
])

// 初始化实时数据
function initRealTimeData() {
  const now = new Date()
  for (let i = 19; i >= 0; i--) {
    const time = new Date(now.getTime() - i * 1000)
    realTimeLabels.value.push(time.toLocaleTimeString())
    realTimeData.value.push(Math.floor(Math.random() * 100))
  }
}

// 更新实时数据
function updateRealTimeData() {
  if (!realTimeEnabled.value)
    return

  const now = new Date()
  realTimeLabels.value.shift()
  realTimeLabels.value.push(now.toLocaleTimeString())

  realTimeData.value.shift()
  realTimeData.value.push(Math.floor(Math.random() * 100))
}

// 开启/关闭实时监控
function toggleRealTime(enabled) {
  if (enabled) {
    realTimeTimer = setInterval(updateRealTimeData, 1000)
  }
  else {
    if (realTimeTimer) {
      clearInterval(realTimeTimer)
      realTimeTimer = null
    }
  }
}

// 更新销售数据
function updateSalesData() {
  // 数据会通过computed自动更新
}

// 销售图表点击事件
function onSalesChartClick(params) {
}

// 获取状态颜色
function getStatusColor(status) {
  const colorMap = {
    已完成: 'green',
    进行中: 'blue',
    待支付: 'orange',
    已取消: 'red',
  }
  return colorMap[status] || 'default'
}

// 快速操作处理
function handleQuickAction(action) {
}

// 生命周期
onMounted(() => {
  initRealTimeData()
  toggleRealTime(realTimeEnabled.value)
})

onUnmounted(() => {
  if (realTimeTimer) {
    clearInterval(realTimeTimer)
  }
})
</script>

<style lang="less" scoped>
.dashboard-container {
  min-height: 100vh;
  padding: 24px;
  background-color: #f0f2f5;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
}

.stat-card {
  .stat-content {
    display: flex;
    align-items: center;

    .stat-icon {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 60px;
      height: 60px;
      margin-right: 16px;
      font-size: 24px;
      color: white;
      border-radius: 12px;

      &.user-icon {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }

      &.order-icon {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      }

      &.revenue-icon {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      }

      &.visit-icon {
        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
      }
    }

    .stat-info {
      flex: 1;

      .stat-number {
        margin-bottom: 4px;
        font-size: 28px;
        font-weight: bold;
        line-height: 1;
        color: #262626;
      }

      .stat-label {
        margin-bottom: 8px;
        font-size: 14px;
        color: #8c8c8c;
      }

      .stat-trend {
        display: flex;
        gap: 4px;
        align-items: center;
        font-size: 12px;

        &.positive {
          color: #52c41a;
        }

        &.negative {
          color: #f5222d;
        }
      }
    }
  }
}

.charts-section {
  margin-bottom: 24px;
}

.chart-row {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 24px;
  margin-bottom: 24px;

  &:last-child {
    margin-bottom: 0;
  }

  &:nth-child(2) {
    grid-template-columns: 1fr 1fr;
  }
}

.chart-card {
  .chart-container {
    height: 300px;

    .chart {
      width: 100%;
      height: 100%;
    }
  }
}

.activity-card {
  .activity-list {
    .activity-item {
      display: flex;
      align-items: flex-start;
      padding: 16px 0;
      border-bottom: 1px solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .activity-avatar {
        margin-right: 12px;
      }

      .activity-content {
        flex: 1;

        .activity-title {
          margin-bottom: 4px;
          font-size: 14px;
          font-weight: 500;
          color: #262626;
        }

        .activity-desc {
          margin-bottom: 4px;
          font-size: 13px;
          color: #8c8c8c;
        }

        .activity-time {
          font-size: 12px;
          color: #bfbfbf;
        }
      }

      .activity-status {
        margin-left: 12px;
      }
    }
  }
}

.quick-actions-card {
  .quick-actions {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;

    .action-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 20px;
      cursor: pointer;
      background: #fafafa;
      border-radius: 8px;
      transition: all 0.3s;

      &:hover {
        background: #f0f0f0;
        transform: translateY(-2px);
      }

      .action-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 40px;
        height: 40px;
        margin-bottom: 8px;
        font-size: 18px;
        color: white;
        border-radius: 8px;
      }

      .action-label {
        font-size: 13px;
        color: #595959;
        text-align: center;
      }
    }
  }
}

.table-section {
  .amount {
    font-weight: 500;
    color: #1890ff;
  }
}

@media (width <= 768px) {
  .dashboard-container {
    padding: 16px;
  }

  .stats-cards {
    grid-template-columns: 1fr;
  }

  .chart-row {
    grid-template-columns: 1fr;
  }

  .quick-actions {
    grid-template-columns: 1fr;
  }
}
</style>
